import {ModalForm, ProFormSelect, ProFormText, ProFormTreeSelect, ProFormDependency, DrawerForm, ProFormRadio } from "@ant-design/pro-components";
import IHttp, {IAxiosResponse} from "@/services/http.service";
import React, {useEffect, useState} from "react";
import {Form, message} from "antd";
import { firstValueFrom } from "rxjs"
import environment from "@/environment";
import IHelper from "@/services/helper.service";

type CreateFormProps = {
  title?: string
  desc?: string
  bili_type?: string
  ks_type?: string
  common_tag?: string[]
  dy_tag?: string[]
  account?: string[]
  video_type?: number
  video_bili_bvid?: string
  video_upload_id?: string
}

type IProps = {
  item: API.PubTaskItem | undefined
  onCancel: () => void
  onRefreshTable: () => void
}

export default function PubTaskCreateForm({item, onCancel, onRefreshTable}: IProps) {
  const [form] = Form.useForm<CreateFormProps>();
  const open = Boolean(item)
  useEffect(() => {
    if (open) {
      setFormData({...item})
    }
  }, [open, item])
  function onTemplateChange(templateDataString: string) {
    if (!templateDataString) return
    const templateData = JSON.parse(templateDataString)
    setFormData(templateData)
  }
  function setFormData(data: Partial<API.PubTaskItem>) {
    const nextData: Partial<CreateFormProps> = {
      title: data.title || "", 
      desc: data.desc || "", 
      common_tag: (data.common_tag || "").split(",").filter(e => e),
      bili_type: data.bili_type || "",
      ks_type: data.ks_type || "",
      dy_tag: (data.dy_tag || "").split(",").filter(e => e),
      account: (data.account || "").split(",").filter(e => e),
      video_upload_id: data.video_upload_id || "",
      video_bili_bvid: data.video_bili_bvid || "",
      video_type: data.video_type || 1,
    }
    Object.keys(nextData).forEach((key: any) => {
      // @ts-ignore
      if (nextData[key].length <= 0) delete nextData[key]
    })
    form.setFieldsValue(nextData)
  }
  return (
    <DrawerForm<CreateFormProps>
      width={360}
      open={open}
      form={form}
      title={item?.id ? "编辑任务" : "新建任务"}
      onFinish={async (values) => {
        const postData: Partial<API.PubTaskItem> = {
          title: values.title || "", 
          desc: values.desc || "",
          bili_type: values.bili_type,
          ks_type: values.ks_type,
          common_tag: (values.common_tag || []).join(","),
          dy_tag: (values.dy_tag || []).join(","),
          account: (values.account || []).join(","),
          video_type: values.video_type || 1,
          video_upload_id: values.video_upload_id || "",
          video_bili_bvid: values.video_bili_bvid || "",
        }
        if (!postData.video_bili_bvid) {
          delete postData.video_bili_bvid
        }
        if (!postData.video_upload_id) {
          delete postData.video_upload_id
        }
        let res: IAxiosResponse | undefined = undefined
        if (item?.id) {
          res = await firstValueFrom(IHttp.updatePubTask(item.id, postData))
        } else {
          res = await firstValueFrom(IHttp.createPubTask(postData))
        }
        if (res?.status) {
          message.success(item?.id ?  "更新成功" : "创建成功")
          onRefreshTable()
        }
        return true
      }}
      drawerProps={{
        destroyOnClose: true,
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      <ProFormSelect
        name="template_id"
        label="使用模板"
        onChange={onTemplateChange}
        request={async (params) => {
          const res = await firstValueFrom(IHttp.getPubTemplateList())
          return res.data.list.map((item: any) => {
            return {
              label: item.title, value: JSON.stringify(item)
            }
          })
        }}
      />
      <ProFormText
        name="title"
        label="标题"
        tooltip="最长为 24 位"
        rules={[{required: true}]}
        placeholder="请输入名称"
      />
      <ProFormText
        name="desc"
        label="介绍"
        rules={[{required: true}]}
        tooltip="最长为 24 位"
        placeholder="请输入介绍"
      />
      
      <ProFormSelect
        name="common_tag"
        label="通用Tag"
        mode="multiple"
        rules={[{required: true}]}
        showSearch
        request={async ({keyWords}) => {
          if (!keyWords) return []
          return [{label: keyWords, value: keyWords}]
        }}
      />
      
      <ProFormTreeSelect
        name="bili_type"
        label="Bili 分类"
        rules={[{required: true}]}
        request={async () => {
          let res = await firstValueFrom(IHttp.getBiliTypeList())
          if (!res.status) {
            return []
          }
          const treeData = res.data.map((item: any) => {
            return {
              ...item, title: item.name, value: item.id,
              disabled: true,
              children: (item.children || []).map((child: any) => {
                return {...child, title: `${child.name} - [${child.desc.substring(0, 10)}...]`, value: `${child.name}_${child.id}`}
              })
            }
          })
          return treeData
        }}
      />
      <ProFormTreeSelect
        name="ks_type"
        label="快手 分类"
        request={async () => {
          let res = await firstValueFrom(IHttp.getKsTypeList())
          if (!res.status) {
            return []
          }
          const treeData = res.data.map((item: any) => {
            return {
              ...item, title: item.firstDomain, value: item.firstDomain,
              disabled: true,
              children: (item.secondDomain || []).map((child: any) => {
                return {title: child, value: `${item.firstDomain}_${child}`}
              })
            }
          })
          return treeData
        }}
      />
      <ProFormSelect
        name="dy_tag"
        label="抖音Tag"
        mode="multiple"
        rules={[{required: true}]}
        showSearch
        request={async ({keyWords}) => {
          if (!keyWords) return []
          const res = await firstValueFrom(IHttp.suggestDyTag(keyWords))
          if (!res.status) return []
          return res.data.map((item: any) => {
            const itemKey = `${item.cha_name}_${new Intl.NumberFormat('zh-CN', { notation: "compact" }).format(item.view_count)}_${item.cid}_${item.group_id}`
            return {label: itemKey, value: itemKey}
            return {
              ...item,
              value: `${item.cid}_${item.group_id}`, 
              label: `${item.cha_name}  ${new Intl.NumberFormat('zh-CN', { notation: "compact" }).format(item.view_count)}`,
            }
          })
        }}
      />
      <ProFormSelect
        name="account"
        label="发布账号"
        showSearch
        mode="multiple"
        debounceTime={300}
        rules={[{required: true}]}
        request={async ({keyWords}) => {
          const res = await firstValueFrom(IHttp.getAccountList({keyword: keyWords}))
          if (!res.status) return[]
          return res.data.list.map((e: API.AccountItem) => {
            const itemKey: string = `${e.name}_${e.id}`
            return {
              label: itemKey, value: itemKey
            }
          })
        }}
      />
      <ProFormRadio.Group 
        name="video_type"
        label="视频类型"
        rules={[{required: true}]}
        options={[
          {
            label: '本地视频',
            value: 1,
          },
          {
            label: "B站视频",
            value: 2,
          },
          {
            label: '抖音视频',
            value: 3,
          },
        ]}
      ></ProFormRadio.Group>
      <ProFormDependency name={["video_type"]}>
        {({video_type}) => {
          if (video_type === 1) {
            return (
              <ProFormSelect
                name="video_upload_id"
                label="选择视频"
                showSearch
                debounceTime={300}
                rules={[{required: true}]}
                request={async ({keyWords}) => {
                  const res = await firstValueFrom(IHttp.getVideoList({keyword: keyWords}))
                  if (!res.status) return[]
                  return res.data.list.map((e: API.VideoItem) => {
                    const itemKey: string = `${e.name}_${e.id}`
                    return {
                      label: itemKey, value: itemKey
                    }
                  })
                }}
              />
            )
          }
          if (video_type === 2) {
            return (
              <ProFormText
                rules={[{required: true}]}
                name="video_bili_bvid"
                label="BVID"
              />
            )
          }
        }}
      </ProFormDependency>
      
      
    </DrawerForm>
  )
}
